<template>
  <div class="print-template-container">
    <el-card 
      v-if="!isElectronAvailable" 
      class="print-service-notice"
      shadow="hover"
    >
      <template #header>
        <div class="notice-header">
          <el-icon class="warning-icon"><Warning /></el-icon>
          <span>打印服务未连接</span>
        </div>
      </template>
      <div class="notice-content">
        <p>部分打印功能可能不可用，请在系统设置中配置打印服务</p>
        <div class="notice-actions">
          <el-button type="primary" @click="checkPrintService" :loading="checkingService">
            <el-icon><RefreshRight /></el-icon> 刷新打印服务状态
          </el-button>
        </div>
      </div>
    </el-card>
    
    <div class="print-actions">
      <el-button type="primary" @click="printPDF" :loading="isPrinting">
        <el-icon><Printer /></el-icon> 打印入库单
      </el-button>
      <el-button type="success" @click="printDirectToPrinter" :loading="isPrinting" title="直接发送到物理打印机，无需预览">
        <el-icon><Printer /></el-icon> 直接打印
      </el-button>
      <el-button type="warning" @click="silentPrint" :loading="isPrinting" title="尽可能减少用户交互的静默打印方式">
        <el-icon><Printer /></el-icon> 静默打印
      </el-button>
      <el-button v-if="isElectronAvailable" type="danger" @click="electronPrint" :loading="isPrinting" title="使用Electron打印服务">
        <el-icon><Printer /></el-icon> Electron打印
      </el-button>
      <el-button v-if="isElectronAvailable" type="info" @click="exportAndPrintImage" :loading="isPrinting" title="将模板导出为图片并打印">
        <el-icon><Picture /></el-icon> 打印图片
      </el-button>
    </div>
    
    <!-- 隐藏的画布容器 -->
    <div class="hidden-canvas-container" style="display: none;">
      <canvas ref="canvasElement" id="printCanvas" width="600" height="800"></canvas>
    </div>
    
    <!-- 打印机选择弹窗 -->
    <el-dialog
      v-model="showPrinterDialog"
      title="选择打印机"
      width="500px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <div v-loading="loadingPrinters">
        <el-form label-width="100px">
          <el-form-item label="打印机:">
            <el-select 
              v-model="selectedPrinter" 
              placeholder="请选择打印机" 
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="printer in printerList"
                :key="printer.name"
                :label="printer.name"
                :value="printer.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="份数:">
            <el-input-number v-model="printCopies" :min="1" :max="10" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelPrinterSelection">取消</el-button>
          <el-button type="primary" @click="confirmPrinterSelection" :disabled="!selectedPrinter">
            打印
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { Printer, Picture, Warning, RefreshRight } from '@element-plus/icons-vue';
import CanvasRenderer from '@/print-sdk/canvasRenderer';
import templateData from './print-inbound.json';

// 移除局部PrintService导入，使用全局的PrintService
// import PrintService from '@/print-sdk/print-service';

// 状态变量
const canvasElement = ref(null);
const isPrinting = ref(false);
const canvasRenderer = new CanvasRenderer();
// Electron相关状态
const isElectronAvailable = ref(false);
const printerList = ref([]);
const selectedPrinter = ref('');
const printCopies = ref(1);
const showPrinterDialog = ref(false);
const loadingPrinters = ref(false);
const checkingService = ref(false);
// 当前PDF Blob
const currentPdfBlob = ref(null);
const parsedTemplate =ref( typeof templateData === 'string' ? JSON.parse(templateData) : templateData);

// 模拟数据 - 替换模板中的占位符
const sampleData = {
  externalOrderNo: "EXT2023120001",
  inboundNo: "IN20230501001",
  inboundType: "采购入库",
  singleQty: "15",
  quantity: "150",
  cargoOwnerName: "李三",
  warehouseName: "北京仓",
  warehouseEntryTime:"2025-02-01 10:30:00",
  productBarcode: "12312312",
  // 表格数据
  inboundTable: [
    {
      serialNumber: "1",
      productName: "笔记本电脑",
      productCode: "NB20230001",
      productBarcode: "6923450657713",
      unit: "台",
      appointmentNumber: "5",
      batchNumber: "BT20230501",
      locationCode: "A-01-01",
      warehouseEntryNumber: "5"
    },
    {
      serialNumber: "2",
      productName: "无线鼠标",
      productCode: "MS20230002",
      productBarcode: "6923450657714",
      unit: "个",
      appointmentNumber: "10",
      batchNumber: "BT20230502",
      locationCode: "A-01-02",
      warehouseEntryNumber: "10"
    },
    {
      serialNumber: "3",
      productName: "显示器",
      productCode: "MN20230003",
      productBarcode: "6923450657715",
      unit: "台",
      appointmentNumber: "3",
      batchNumber: "BT20230503",
      locationCode: "A-01-03",
      warehouseEntryNumber: "3"
    }
  ]
};

// 打印PDF
const printPDF = async () => {
  // 防止重复点击
  if (isPrinting.value) return;
  
  try {
    isPrinting.value = true;
    
    // 检查PrintService是否可用
    if (!window.PrintService) {
      ElMessage.error('打印服务未初始化，请先在系统设置中配置打印服务');
      return;
    }
    
    // 使用全局PrintService
    await window.PrintService.printPDF(
      templateData,
      sampleData,
      canvasElement.value,
      { filename: '入库单.pdf' }
    );
  } catch (error) {
    console.error('打印PDF失败:', error);
    ElMessage.error('打印失败: ' + error.message);
  } finally {
    isPrinting.value = false;
  }
};

// 直接打印到打印机
const printDirectToPrinter = async () => {
  // 防止重复点击
  if (isPrinting.value) return;
  
  try {
    isPrinting.value = true;
    
    // 检查PrintService是否可用
    if (!window.PrintService) {
      ElMessage.error('打印服务未初始化，请先在系统设置中配置打印服务');
      return;
    }
    
    // 获取默认打印机
    const printer = window.PrintService.defaultPrinter;
    
    // 使用全局PrintService
    await window.PrintService.printDirectToPrinter(
      templateData,
      sampleData,
      canvasElement.value,
      { 
        printer: printer,
        filename: '入库单.pdf'
      }
    );
  } catch (error) {
    console.error('发送到打印机失败:', error);
    ElMessage.error('发送到打印机失败: ' + (error.message || '未知错误'));
  } finally {
    isPrinting.value = false;
  }
};

// 静默打印功能（尽可能减少用户交互）
const silentPrint = async () => {
  // 防止重复点击
  if (isPrinting.value) return;
  
  try {
    isPrinting.value = true;
    
    // 检查PrintService是否可用
    if (!window.PrintService) {
      ElMessage.error('打印服务未初始化，请先在系统设置中配置打印服务');
      return;
    }
    
    // 获取默认打印机
    const printer = window.PrintService.defaultPrinter;
    
    // 使用全局PrintService
    await window.PrintService.silentPrint(
      templateData,
      sampleData,
      canvasElement.value,
      { 
        printer: printer,
        filename: '入库单.pdf'
      }
    );
  } catch (error) {
    console.error('静默打印失败:', error);
    ElMessage.error('发送到打印机失败: ' + (error.message || '未知错误'));
  } finally {
    isPrinting.value = false;
  }
};

// 生成PDF Blob
const generatePDFBlob = async (templateData, data, canvasElement) => {
  try {
    // 使用全局PrintService
    return await window.PrintService.generatePDFBlob(templateData, data, canvasElement);
  } catch (error) {
    console.error('生成PDF Blob失败:', error);
    ElMessage.error(`生成PDF失败: ${error.message || '未知错误'}`);
    throw error;
  }
};

// 向PrintService注册显示打印机选择对话框的回调函数
onMounted(async () => {
  console.log('打印模板组件已挂载');
  
  // 检查全局PrintService是否已初始化，如果未初始化，添加重试机制
  let retryCount = 0;
  const maxRetries = 3;
  
  const initPrintService = async () => {
    if (window.PrintService) {
      console.log('全局PrintService已初始化');
      
      // 从全局PrintService获取打印状态和默认打印机
      isElectronAvailable.value = window.PrintService.isServiceAvailable();
      
      // 设置对话框回调
      window.PrintService.setShowPrinterDialogCallback(async (printers) => {
        // 保存打印机列表
        printerList.value = printers;
        
        // 默认选中上次使用的打印机
        selectedPrinter.value = window.PrintService.defaultPrinter || (printers.length > 0 ? printers[0].name : '');
        
        // 显示对话框
        showPrinterDialog.value = true;
        
        // 返回一个Promise，等待用户选择打印机
        return new Promise((resolve) => {
          // 保存resolve函数以便在confirmPrinterSelection中调用
          window.resolvePrinterSelection = (printer) => {
            resolve(printer);
          };
        });
      });
      
      if (window.PrintService.defaultPrinter) {
        console.log(`已配置默认打印机: ${window.PrintService.defaultPrinter}`);
      } else {
        console.log('未设置默认打印机');
      }
      
      // 刷新打印机列表
      loadPrinters();
      
      return true;
    } else {
      if (retryCount < maxRetries) {
        retryCount++;
        console.log(`全局PrintService未初始化，第${retryCount}次重试...`);
        // 延迟1秒后重试
        await new Promise(resolve => setTimeout(resolve, 1000));
        return await initPrintService();
      } else {
        console.error('全局PrintService未初始化，重试次数已达上限');
        ElMessage.warning('打印服务未初始化，请先在系统设置中配置打印服务');
        return false;
      }
    }
  };
  
  await initPrintService();
});

// 确认打印机选择
const confirmPrinterSelection = () => {
  if (!selectedPrinter.value) {
    ElMessage.warning('请选择打印机');
    return;
  }
  
  // 关闭对话框
  showPrinterDialog.value = false;
  
  // 如果存在resolve函数，调用它返回选择的打印机
  if (window.resolvePrinterSelection) {
    window.resolvePrinterSelection(selectedPrinter.value);
    window.resolvePrinterSelection = null;
  }
};

// 取消打印机选择
const cancelPrinterSelection = () => {
  showPrinterDialog.value = false;
  
  // 如果存在resolve函数，调用它返回null表示取消
  if (window.resolvePrinterSelection) {
    window.resolvePrinterSelection(null);
    window.resolvePrinterSelection = null;
  }
};

// 使用Electron打印服务
const electronPrint = async () => {
  // 防止重复点击
  if (isPrinting.value) return;
  
  try {
    isPrinting.value = true;
    
    // 检查PrintService是否可用
    if (!window.PrintService) {
      ElMessage.error('打印服务未初始化，请先在系统设置中配置打印服务');
      return;
    }
    
    // 使用全局PrintService
    await window.PrintService.printTemplate(
      templateData,
      sampleData,
      canvasElement.value,
      {
        copies: printCopies.value,
        width: parsedTemplate.value.canvas.width,
        height: parsedTemplate.value.canvas.height
      }
    );
  } catch (error) {
    console.error('打印失败:', error);
    ElMessage.error('打印失败: ' + (error.message || '未知错误'));
  } finally {
    isPrinting.value = false;
  }
};

// 修改exportAndPrintImage方法
const exportAndPrintImage = async () => {
  // 防止重复点击
  if (isPrinting.value) return;
  
  try {
    isPrinting.value = true;
    
    // 检查PrintService是否可用
    if (!window.PrintService) {
      ElMessage.error('打印服务未初始化，请先在系统设置中配置打印服务');
      return;
    }
    
    // 使用全局PrintService
    await window.PrintService.printTemplateAsImage(
      templateData,
      sampleData,
      canvasElement.value,
      {
        copies: printCopies.value,
        width: parsedTemplate.value.canvas.width,
        height: parsedTemplate.value.canvas.height
      }
    );
  } catch (error) {
    console.error('图片打印失败:', error);
    ElMessage.error('图片打印失败: ' + (error.message || '未知错误'));
  } finally {
    isPrinting.value = false;
  }
};

// 组件卸载前清理资源
onBeforeUnmount(() => {
  // 清理fabric实例
  if (canvasRenderer.fabricInstance) {
    try {
      canvasRenderer.fabricInstance.dispose();
    } catch (error) {
      console.error('清理资源失败:', error);
    }
  }
});

// 加载打印机列表
const loadPrinters = async () => {
  loadingPrinters.value = true;
  try {
    // 检查PrintService是否可用
    if (!window.PrintService) {
      console.error('打印服务未初始化，无法加载打印机列表');
      loadingPrinters.value = false;
      return;
    }
    
    printerList.value = await window.PrintService.getPrinters();
    
    // 如果获取到打印机列表，更新选中的打印机
    if (printerList.value && printerList.value.length) {
      // 如果有默认打印机，使用默认打印机
      if (window.PrintService.defaultPrinter) {
        selectedPrinter.value = window.PrintService.defaultPrinter;
      } else {
        // 否则选择第一个打印机
        selectedPrinter.value = printerList.value[0].name;
      }
    } else {
      // 打印机列表为空
      ElMessage.warning('未检测到可用打印机，请检查打印机连接或在系统设置中配置打印服务');
    }
  } catch (error) {
    console.error('获取打印机列表失败:', error);
    ElMessage.error('获取打印机列表失败: ' + (error.message || '未知错误'));
  } finally {
    loadingPrinters.value = false;
  }
};

// 检查打印服务状态
const checkPrintService = async () => {
  if (checkingService.value) return;
  
  checkingService.value = true;
  
  try {
    console.log('正在刷新打印服务状态...');
    
    if (window.PrintService) {
      console.log('全局PrintService已存在，检查连接状态');
      
      // 刷新状态
      isElectronAvailable.value = window.PrintService.isServiceAvailable();
      
      if (isElectronAvailable.value) {
        ElMessage.success('打印服务连接正常');
        // 刷新打印机列表
        await loadPrinters();
      } else {
        ElMessage.warning('打印服务连接异常，请在系统设置中重新配置');
      }
    } else {
      console.error('全局PrintService未初始化');
      ElMessage.error('打印服务未初始化，请在系统设置中配置打印服务');
    }
  } catch (error) {
    console.error('检查打印服务失败:', error);
    ElMessage.error('检查打印服务失败: ' + (error.message || '未知错误'));
  } finally {
    checkingService.value = false;
  }
};
</script>

<style scoped>
.print-template-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 200px;
}

/* 打印服务提示框样式 */
.print-service-notice {
  width: 100%;
  margin-bottom: 20px;
  border-left: 4px solid #E6A23C;
}

.notice-header {
  display: flex;
  align-items: center;
  color: #E6A23C;
  font-weight: bold;
}

.warning-icon {
  margin-right: 8px;
  font-size: 18px;
}

.notice-content {
  color: #606266;
}

.notice-actions {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.print-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.hidden-canvas-container {
  position: absolute;
  visibility: hidden;
  pointer-events: none;
}

/* 打印机选择对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 